package com.sh.common.context;

import com.google.common.base.Charsets;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;

import java.io.*;

public class RequestWrapper extends HttpServletRequestWrapper {

	private byte[] cachedBody;

	public RequestWrapper(HttpServletRequest request) throws IOException {
		super(request);
		if (isMultipart(request)) {
			// Skip caching for multipart requests
			this.cachedBody = null;
		} else{
			// 缓存请求体
			InputStream requestInputStream = request.getInputStream();
			this.cachedBody = requestInputStream.readAllBytes();
		}

	}
	private boolean isMultipart(HttpServletRequest request) {
		return request.getContentType() != null && request.getContentType().startsWith("multipart/");
	}
	@Override
	public ServletInputStream getInputStream() throws IOException {
		return new CachedBodyServletInputStream(this.cachedBody);
	}

	@Override
	public BufferedReader getReader() throws IOException {
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.cachedBody);
		return new BufferedReader(new InputStreamReader(byteArrayInputStream));
	}

	private static class CachedBodyServletInputStream extends ServletInputStream {

		private final ByteArrayInputStream byteArrayInputStream;

		public CachedBodyServletInputStream(byte[] cachedBody) {
			this.byteArrayInputStream = new ByteArrayInputStream(cachedBody);
		}

		@Override
		public boolean isFinished() {
			return byteArrayInputStream.available() == 0;
		}

		@Override
		public boolean isReady() {
			return true;
		}

		@Override
		public void setReadListener(ReadListener listener) {
			// 不需要实现此方法
		}

		@Override
		public int read() throws IOException {
			return byteArrayInputStream.read();
		}
	}
}
